﻿using B.R.RabbitRoot.Domain;
using B.R.RabbitRoot.ErrorCode;
using B.R.RabbitRoot.Write.API.Applications.Commandhandlers.ImgCommandHandlers;
using B.R.RabbitRoot.Write.API.Applications.Commands.FarmInfoCommands;
using B.R.RabbitRoot.Write.API.Applications.Commands.FarmingCommands;
using B.R.RabbitRoot.Write.API.Applications.Commands.HealthCareCommands;
using B.R.RabbitRoot.Write.API.Applications.Commands.ImgCommands;
using B.R.RabbitRoot.Write.API.Applications.Commands.SourceCommands;
using MediatR;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System.Net.Http.Headers;

namespace B.R.RabbitRoot.Write.API.Controllers
{
    /// <summary>
    /// 写的api
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ManagermentController : ControllerBase
    {
        private readonly IMediator mediator;

        public ManagermentController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        /// <summary>
        /// 溯源的添加
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> CreamSource(SourceCreamCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadImages(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("文件不能为空");
            }

            // 限制文件类型
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png" };
            var fileExtension = Path.GetExtension(file.FileName).ToLower();
            if (!allowedExtensions.Contains(fileExtension))
            {
                return BadRequest("只允许上传图片文件（.jpg, .jpeg, .png）");
            }

            // 限制文件大小
            if (file.Length > 5 * 1024 * 1024) // 限制为 5MB
            {
                return BadRequest("文件大小不能超过 5MB");
            }

            // 生成唯一文件名
            string uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
            string saveKey = "Pic/" + uniqueFileName; // 保存路径
            string bucket = "rabbitpicture"; // 存储空间名称

            // 初始化七牛云认证
            Mac mac = new Mac(accessKey: "qf1_7lFRr5DetsVMkUrvsGCT_x_MPNq8nkk2ayCa", secretKey: "kIPTqPMcvs37-0lGEStEKsKpQxGO-s0NhGp0Eojh");

            // 设置上传策略rabbitpicture
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = bucket + ":" + saveKey;
            var imgbase = saveKey;
            // 生成上传凭证
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            // 配置上传管理器
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_North; // 设置上传区域
            config.UseHttps = true; // 使用 HTTPS
            config.UseCdnDomains = true; // 使用 CDN 加速
            config.ChunkSize = ChunkUnit.U512K; // 设置分块大小

            // 实例化表单上传对象
            FormUploader target = new FormUploader(config);

            // 上传文件
            HttpResult result = await Task.Run(() => target.UploadStream(file.OpenReadStream(), saveKey, token, null));

            // 检查上传结果
            if (result.Code == 200)
            {
                string fileUrl = $"https://{bucket}.qiniu.com/{saveKey}";
                return Ok(new { message = "上传成功", url = fileUrl, imgbase = "http://srmgvpbrq.hb-bkt.clouddn.com/" + imgbase });
            }
            else
            {
                return BadRequest("上传失败：" + result.Text);
            }
        }


        /// <summary>
        /// 多图片上传
        /// </summary>
        /// <param name="fileser"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        public List<Object> UploadQiniu([FromForm(Name = "file")] List<IFormFile> fileser)
        {
            Mac mac = new Mac("qf1_7lFRr5DetsVMkUrvsGCT_x_MPNq8nkk2ayCa", "kIPTqPMcvs37-0lGEStEKsKpQxGO-s0NhGp0Eojh"); // 替换为您七牛云账号的访问密钥和密钥
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = "rabbitpicture";//图片存放七牛云地址
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); // 生成上传凭证，凭证包含了上传策略信息
            IFormFileCollection files = Request.Form.Files;
            Config config = new Config()
            {
                Zone = Zone.ZONE_CN_North,//默认华北 根据选择的不同输入不同的地区
                UseHttps = true
            };
            config.UseCdnDomains = true; // 使用 CDN 域名加速上传
            var res = Request.Form.ToArray();

            FormUploader upload = new FormUploader(config);
            HttpResult result = new HttpResult();
            List<Object> list = new List<Object>();
            foreach (IFormFile file in fileser)//获取多个文件列表集合
            {
                if (file.Length > 0)
                {
                    var _fileName = ContentDispositionHeaderValue
                                    .Parse(file.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    var _qiniuName = "Pic/" + DateTime.Now.ToString("yyyyMMddHHmmssffffff") + file.FileName;//重命名文件加上时间戳
                    Stream stream = file.OpenReadStream();
                    result = upload.UploadStream(stream, _qiniuName, token, null);
                    if (result.Code == 200)
                    {
                        list.Add(new { fileName = _fileName, qiniuName = _qiniuName, uploadTime = DateTime.Now });
                    }
                    else
                    {
                        throw new Exception(result.RefText);//上传失败错误信息
                    }
                }
            }
            return list;
        }
        /// <summary>
        /// 溯源的删除
        /// </summary>  
        /// <param name="sourceInfoId"></param>
        /// <returns></returns>            
        [HttpPost]
        public async Task<APIResult<int>> SourceInfoDelete(SourceDeleteCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary> 
        /// 溯源的修改  
        /// </summary> 
        /// <param name="command"></param> 
        /// <returns></returns> 
        [HttpPost]
        public async Task<APIResult<int>> SourceInfoUpdate(SoureceUpdateCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 图片的添加
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> Imgrep(ImageTableCreamCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 图片的显示
        /// </summary>
        /// <param name="sourceInfoId"></param>
        /// <param name="primaryCategory"></param>
        /// <param name="secondaryCategory"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<ImageTable>>> Getimgrep(int sourceInfoId)
        {
            ImageTableQueryCommand command = new ImageTableQueryCommand();
            command.SourceInfoId = sourceInfoId;
            return await mediator.Send(command);
        }
        /// <summary>
        /// 图片的删除
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<int>> Delimgrep(string secondaryCategory)
        {
            ImageTableDeleteCommandHandler commandHandler = new ImageTableDeleteCommandHandler();
            commandHandler.SecondaryCategory = secondaryCategory;
            return await mediator.Send(commandHandler);
        }
        /// <summary>
        /// 养殖信息的添加
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> FarmingCream(FarmingCreamCommand command)
        { 
            return await mediator.Send(command);
        }
        /// <summary>
        /// 保健信息的添加
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> HealthCareInfoCream(HealthCareCreamCommand command)
        { 
            return await mediator.Send(command);
        }
        /// <summary>
        /// 保健信息的修改
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> HealthCareInfoUpdate(HealthCareUpdateCommand command)
        { 
            return await mediator.Send(command);
        }
        /// <summary>
        /// 保健信息的删除
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> HealthCareInfoDelete(HealthCareDeleteCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 企业信息的添加
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> FarminfoCream(FarmInfoCreamCommand command)
        { 
            return await mediator.Send(command);
        }
    }
}
